import { DomController } from "./dom_controller";
import { LinkedList } from "../common/linked_list";

// 基础元素
export interface BaseElement {
    parentElement?: ContextElement;
    dom?: DomController;
}

// 上下文元素
export interface ContextElement extends BaseElement {
    type: "context";
    // 上下文名称
    label: string;
    // 子元素
    children: LinkedList<Element>;
    // 上下文元素的key
    key: number;
}

/**
 * 下一行元素
 */
export interface NextLineElement extends BaseElement {
    type: 'nextLine';
    // 缩进值
    indent: number;
}

/**
 * label元素，显示为独立的标签，如json/array/object
 */
export interface LabelElement extends BaseElement {
    type: "label";
    // label内容
    label: string;
}

/**
 * split元素，分隔符可以理解为语言中的: ; {}
 */
export interface SplitElement extends BaseElement {
    type: "split";
    // 分隔符内容
    text: string;
    leftMargin: number;
    rightMargin: number;
}

/**
 * 输入框元素
 */
export interface InputElement extends BaseElement {
    type: "input",
    // 输入框的值
    inputValue: string;
    // 输入框的key
    key: number;
}

/**
 * 界面显示的元素
 */
export type Element = ContextElement | NextLineElement | LabelElement | SplitElement | InputElement;
export type MainElement = ContextElement | InputElement;
export type ElementType = Element["type"];
export type ElementFactoryMap = {
    [K in ElementType]?: (element: Extract<Element, { type: K }>) => DomController | undefined;
}

export const findLastDom = (element: Element): HTMLElement | undefined => {
  // context的children不能为空
  // 其他元素的dom不能为空
  while (element.type === 'context') {
    const children = element.children;
    const lastNode = children.getTail();
    if (!lastNode) {
      throw new Error('find insert dom failed, context children is empty');
    }
    element = lastNode.value;
  }
  if (!element.dom) {
    // 后续可以考虑prev元素，避免element没有dom的情况
    throw new Error('find insert dom failed, element dom is empty');
  }
  return element.dom.getLastDom();
}
